package org.darcy.app.config;

import static com.google.common.collect.Lists.newArrayList;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.darcy.common.config.SysConfig;
import org.darcy.common.constants.Constants;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger配置组件
 */
@Configuration
@EnableSwagger2
@ConfigurationProperties(prefix = "api.doc")
public class SwaggerConfig {

	@Value("${swagger.basic.enable}")
	private Boolean swaggerEnabled;

	@Autowired
	private SysConfig SysConfig;

	@Bean
	public Docket docket() {
		return new Docket(DocumentationType.SWAGGER_2).groupName("app").host(SysConfig.getDomain()).apiInfo(apiInfo())
				.enable(swaggerEnabled).select().build().securitySchemes(security())
				.securityContexts(securityContexts()).pathMapping("/");
	}

	private List<ApiKey> security() {
		return newArrayList(
				new ApiKey(Constants.HEADER_AUTHORIZATION_KEY, Constants.HEADER_AUTHORIZATION_KEY, "header"));
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder().title("TheShop 商城系统").description("TheShop 商城系统APP前端接口")
				.termsOfServiceUrl("http://host:port").version("1.0.0").build();
	}

	private List<SecurityContext> securityContexts() {
		List<SecurityContext> res = new ArrayList<>();
		res.add(SecurityContext.builder().securityReferences(defaultAuth()).build());
		return res;
	}

	private List<SecurityReference> defaultAuth() {
		List<SecurityReference> res = new ArrayList<>();
		AuthorizationScope authorizationScope = new AuthorizationScope("global", Constants.HEADER_AUTHORIZATION_KEY);
		AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
		authorizationScopes[0] = authorizationScope;
		res.add(new SecurityReference(Constants.HEADER_AUTHORIZATION_KEY, authorizationScopes));
		return res;
	}
	
	@Bean
	public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
		return new BeanPostProcessor() {

			@Override
			public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
				if (bean instanceof WebMvcRequestHandlerProvider) {
					customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
				}
				return bean;
			}

			private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(
					List<T> mappings) {
				List<T> copy = mappings.stream().filter(mapping -> mapping.getPatternParser() == null)
						.collect(Collectors.toList());
				mappings.clear();
				mappings.addAll(copy);
			}

			@SuppressWarnings("unchecked")
			private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
				try {
					Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
					field.setAccessible(true);
					return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					throw new IllegalStateException(e);
				}
			}
		};
	}
}
